﻿/*******************************************************************************
 * Copyright @ 2017 YunSpace.Framework 版权所有
 * Author: GaoTang
 * Description: YunSpace 快速开发平台
 * Website：http://www.yunspace.com.cn
*********************************************************************************/
#region USING SYSTEM

using System;
using YunSpace.Core;
using YunSpace.Domain.Entity.Topic;
using YunSpace.Domain.IRepository.Topic;
using YunSpace.Repository.Topic;
using System.Collections.Generic;
using System.Linq;
using YunSpace.Application.SystemManage;
using YunSpace.Core.Extend;
using YunSpace.Data;
using YunSpace.Domain.ViewModel.SiteMgr;
using YunSpace.Domain.ViewModel.System;
using YunSpace.Domain.ViewModel.Topic;

#endregion

namespace YunSpace.Application.Topic
{
    public class ArticleApp
    {
        #region const

        const string articleKey = "Topic_ArticleTypes_Article";
        const string miniSiteKey = "Topic_ArticleTypes_MiniSite";
        const string activityCaseKey = "Topic_ArticleTypes_ActivityCase";
        const string goodCaseKey = "Topic_ArticleTypes_GoodCase";
        const string specialKey = "Topic_ArticleTypes_Special";
        const string newsKey = "Topic_ArticleTypes_News";
        const string Topic_BannerKey = "Topic_Banner";
        const string Topic_SourceKey = "Topic_Source";

        #endregion const


        private readonly ItemsApp _itemsApp = new ItemsApp();
        private IArticleRepository service = new ArticleRepository();
        private static readonly List<KeyValuePair<string, string>> SpaceCache = new List<KeyValuePair<string, string>>();
        private readonly ItemsDetailApp itemsDetailApp = new ItemsDetailApp();

        #region ctor

        static ArticleApp()
        {
            try
            {
                LoadSpaceCache();
            }
            catch (Exception e)
            {
                throw;
            }
        }

        #endregion ctor




        public List<ArticleEntity> GetList(string keyword = "")
        {
            var expression = ExtLinq.True<ArticleEntity>();
            // if (!string.IsNullOrEmpty(keyword))
            // {
            //     expression = expression.And(t => t.F_FullName.Contains(keyword));
            //     expression = expression.Or(t => t.F_EnCode.Contains(keyword));
            // }
            // expression = expression.And(t => t.F_Category == 2);
            return service.IQueryable(expression).OrderBy(t => t.F_Id).ToList();
        }

        public ArticleEntity GetForm(string keyValue)
        {
            return service.FindEntity(keyValue);
        }

        public void DeleteForm(string keyValue)
        {
            service.Delete(t => t.F_Id == keyValue);
        }

        public void SubmitForm(ArticleEntity articleEntity, string keyValue)
        {
            if (!string.IsNullOrEmpty(keyValue))
            {
                articleEntity.Modify(keyValue);
                service.Update(articleEntity);
            }
            else
            {
                articleEntity.Create();
                // articleEntity.F_Category = 2;
                service.Insert(articleEntity);
            }
        }

        public List<ArticleDto> GetArticles(GetGridJsonRequest request, Pagination pagination)
        {
            //service.GetArticles(pagination);
            var articles = service.GetArticles(request,pagination);

            foreach (var articleDto in articles)
            {
                var fClass = articleDto.Class;
                var banners = itemsDetailApp.GetItemList(Topic_BannerKey);

                if (!fClass.IsNullOrEmpty())
                {
                    var fClasses = fClass.Split(',');

                    if (fClasses.Any())
                    {
                        var classStr = "";

                        foreach (var t in fClasses)
                        {
                            var firstBanner = banners.FirstOrDefault(x => x.F_ItemCode == t);
                            if (firstBanner == null)
                            {
                                classStr += t + ",";
                            }
                            else
                            {
                                classStr += firstBanner.F_ItemName + ",";
                            }
                        }

                        if (classStr.EndsWith(","))
                        {
                            classStr = classStr.Remove(classStr.Length - 1);
                        }
                        articleDto.Class = classStr;
                    }
                }

                var source = articleDto.Source;
                var sources = itemsDetailApp.GetItemList(Topic_SourceKey);

                if (!source.IsNullOrEmpty())
                {
                    var firstSource = sources.FirstOrDefault(x => x.F_ItemCode == source);

                    if (firstSource != null)
                    {
                        articleDto.Source = firstSource.F_ItemName;
                    }
                }


                var itemsDetails = new List<ItemsDetailActionModel>();

                itemsDetails.AddRange(itemsDetailApp.GetItemList(articleKey));
                itemsDetails.AddRange(itemsDetailApp.GetItemList(miniSiteKey));
                itemsDetails.AddRange(itemsDetailApp.GetItemList(activityCaseKey));
                itemsDetails.AddRange(itemsDetailApp.GetItemList(goodCaseKey));
                itemsDetails.AddRange(itemsDetailApp.GetItemList(specialKey));
                itemsDetails.AddRange(itemsDetailApp.GetItemList(newsKey));

                var type = itemsDetails.FirstOrDefault(x => x.F_ItemCode == articleDto.Type);

                if (type != null)
                {
                    articleDto.Type = type.F_ItemName;
                }

                foreach (var keyValuePair in SpaceCache)
                {
                    if (keyValuePair.Key == articleDto.SpaceId)
                    {
                        articleDto.Space = keyValuePair.Value;
                        break;
                    }
                }

                var cities = GetAllCitys();

                if (!articleDto.RecommendCity.IsNullOrEmpty())
                {
                    var firstCity = cities.FirstOrDefault(x => x.F_Id == articleDto.RecommendCity);

                    if (firstCity != null)
                    {
                        articleDto.RecommendCity = firstCity.F_FullName;
                    }
                }
            }

            return articles;
        }

        /// <summary>
        /// 获取空间
        /// </summary>
        /// <returns></returns>
        public List<KeyValuePair<string, string>> GetSpaceMaps()
        {
            return SpaceCache;
        }

        /// <summary>
        /// 获取所有城市
        /// </summary>
        /// <returns></returns>
        public List<AreaModel> GetAllCitys()
        {
            List<AreaModel> citys = CacheFactory.Cache().Get("City") as List<AreaModel>;
            if (citys == null)
            {
                using (var db = new RepositoryBase())
                {
                    string strSql = @"select a.F_Id,a.F_ParentId,a.F_EnCode,a.F_FullName  from Sys_Area a where a.F_Layers=2";
                    citys = db.FindList<AreaModel>(strSql);
                    CacheFactory.Cache().Insert("City", citys);
                }
            }
            return citys;
        }

        #region private static

        /// <summary>
        /// 加载空间缓存
        /// </summary>
        private static void LoadSpaceCache()
        {
            var sql = @"SELECT F_Id AS Name, title AS Value
                        FROM SL_Space
                        WHERE state = 1";
            var app = new ArticleRepository();
            var data = app.GetColumnList<NameValuePaire<string, string>>(sql);

            foreach (var nameValuePaire in data)
            {
                SpaceCache.Add(new KeyValuePair<string, string>(nameValuePaire.Name, nameValuePaire.Value));
            }
        }

        #endregion private static


        private class NameValuePaire<TName, TValue>
        {
            public TName Name { get; set; }

            public TValue Value { get; set; }
        }
    }


}

